import pyautogui
import time
# import os  # 已移除未使用的导入
import keyboard
import threading
import fun
import mouse_fun

# 全局暂停标志
is_paused = False
# 全局掉线检测标志
diaoxian_detected = False
# 全局停止标志
should_stop = False
# 监控线程
monitor_thread = None
# 监控控制标志
monitor_active = True

def check_should_stop():
    """检查是否应该停止程序"""
    global should_stop
    return should_stop

def set_stop_flag():
    """设置停止标志"""
    global should_stop, is_paused
    should_stop = True
    is_paused = False  # 重置暂停状态，确保程序能响应停止信号
    print("停止信号已设置，暂停状态已重置")

def toggle_pause():
    """切换暂停状态"""
    global is_paused, diaoxian_detected, should_stop
    
    # 如果停止信号被设置，不允许暂停/继续操作
    if should_stop:
        print("停止信号已设置，无法切换暂停状态")
        return
    
    is_paused = not is_paused
    if is_paused:
        print("程序已暂停，按F8继续...")
        # 暂停时激活自动化工具窗口到前台
        fun.activate_automation_window()
        # 暂停时停止监控以减少CPU占用
        stop_monitoring()
    else:
        print("程序继续执行...")
        # 继续时将自动化工具窗口最小化到后台
        fun.send_automation_window_to_back()
        # 如果是因为掉线检测而暂停的，重置掉线检测标志并重新启动监控
        if diaoxian_detected:
            diaoxian_detected = False
            start_monitoring()
        else:
            # 重新启动监控
            start_monitoring()

def wait_if_paused():
    """如果程序暂停，则等待直到继续"""
    global is_paused, should_stop
    while is_paused:
        # 检查停止信号，如果应该停止则直接返回
        if should_stop:
            print("检测到停止信号，退出暂停等待")
            return
        
        # 在GUI环境中使用更精确的时间控制
        start_time = time.time()
        time.sleep(0.1)  # 短暂休眠，避免CPU占用过高
        
        # 确保实际休眠时间接近预期时间
        actual_sleep = time.time() - start_time
        if actual_sleep < 0.08:  # 如果实际休眠时间太短，补充休眠
            time.sleep(0.1 - actual_sleep)

def monitor_diaoxian():
    """实时监控屏幕上是否出现diaoxian.png"""
    global diaoxian_detected, is_paused, monitor_active
    print("掉线监控线程已启动，使用低频率监控模式...")
    while monitor_active:
        try:
            # 检测屏幕上是否出现diaoxian.png
            # 使用更低的置信度和更长的检查间隔来减少CPU占用
            location = pyautogui.locateOnScreen("static/images/diaoxian.png", confidence=0.7)
            if location and not diaoxian_detected:
                print("检测到掉线图片！程序暂停执行...")
                diaoxian_detected = True
                is_paused = True
                print("请按F8键重新开始程序执行")
                # 不退出循环，继续监控
        except Exception:
            # 如果找不到图片，继续监控
            pass
        time.sleep(3)  # 每3秒检查一次，进一步减少CPU占用

def start_monitoring():
    """启动掉线监控线程"""
    global monitor_thread, monitor_active
    monitor_active = True
    if monitor_thread is None or not monitor_thread.is_alive():
        monitor_thread = threading.Thread(target=monitor_diaoxian, daemon=True)
        monitor_thread.start()
        print("掉线监控已启动")

def stop_monitoring():
    """停止掉线监控线程"""
    global monitor_active
    monitor_active = False
    print("掉线监控已停止")

def check_stop_signals_multi_level():
    """
    多层级置信度比对停止信号
    从最高置信度0.95 对比两次图片一共验证12次
    在特定区域内进行比对，而不是整个屏幕
    返回True表示检测到停止信号，False表示未检测到
    """
    stop_images = [
        "static/images/stop.png",
        "static/images/stop2.png", 
        "static/images/stop3.png",
        "static/images/stop4.png",
        "static/images/stop5.png",
        "static/images/stop6.png"
    ]
    
    # 只查找一次test.png图片位置，不移动鼠标
    try:
        location = pyautogui.locateOnScreen("static/images/test.png", confidence=0.8)
        if location:
            current_x, current_y = location.left, location.top
            print(f"找到test.png图片位置: ({current_x}, {current_y})")
        else:
            print("未找到test.png图片，无法确定搜索区域")
            return False
    except Exception as e:
        print(f"查找test.png图片时出错: {e}")
        return False
    
    # 定义比对区域：从找到的图片位置开始，宽度600像素，高度600像素
    search_region = (int(current_x), int(current_y), 600, 600)
    
    # 截取search_region区域的图片并保存
    try:
        screenshot = pyautogui.screenshot(region=search_region)
        screenshot.save("static/images/search_region_screenshot.png")
        print(f"已保存搜索区域截图到: static/images/search_region_screenshot.png")
        print(f"搜索区域坐标: {search_region}")
    except Exception as e:
        print(f"保存搜索区域截图时出错: {e}")
    
    print(f"在区域 {search_region} 内进行比对...")
    
    # 多层级置信度比对：0.9 -> 0.8 -> 0.7
    confidence_levels = [0.95,0.95]
    
    for confidence in confidence_levels:
        print(f"正在使用置信度 {confidence} 进行比对...")
        
        for i, image_path in enumerate(stop_images, 1):
            try:
                # 在指定区域内查找图片，而不是整个屏幕
                result = pyautogui.locateOnScreen(image_path, confidence=confidence, region=search_region)
                if result:
                    print(f"检测到停止信号（置信度{confidence}），图片: {image_path}")
                    print(f"匹配位置: {result}")
                    
                    # 额外验证：截取匹配区域进行二次确认
                    try:
                        match_region = (int(result.left), int(result.top), int(result.width), int(result.height))
                        match_screenshot = pyautogui.screenshot(region=match_region)
                        # 使用固定文件名，每次覆盖之前的文件
                        match_filename = "static/images/match_confirmation.png"
                        match_screenshot.save(match_filename)
                        print(f"已保存匹配确认截图: {match_filename}")
                        
                        # 同时保存一个带时间戳的版本用于调试
                        import datetime
                        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
                        timestamp_filename = f"static/images/match_confirmation_{timestamp}.png"
                        match_screenshot.save(timestamp_filename)
                        print(f"已保存带时间戳的确认截图: {timestamp_filename}")
                        
                    except Exception as e:
                        print(f"保存匹配确认截图时出错: {e}")
                    
                    return True  # 检测到停止信号
            except Exception as e:
                print(f"比对第{i}张图片时出错: {e}")
                continue
        
        # 如果当前置信度下所有图片都没匹配到，等待一小段时间再降低置信度
        if confidence > 0.7:
            time.sleep(0.1)
    
    print("所有置信度级别都未检测到停止信号")
    return False  # 未检测到停止信号

# 注册F8键监听
keyboard.on_press_key("F8", lambda _: toggle_pause())



# 初始化
def init():
    """初始化企业微信，使用简化的启动逻辑"""
    print("🚀 开始初始化企业微信...")

    # 检查企业微信窗口是否在前台
    print("🔍 检查企业微信窗口状态...")
    if fun.check_window_activated():
        print("✅ 企业微信窗口已在激活状态，开始最大化...")
        if fun.maximize_wechat_window():
            print("✅ 企业微信窗口已最大化")
        else:
            print("⚠️ 企业微信窗口最大化失败")
    else:
        print("⚠️ 未找到企业微信窗口或未在前台，直接从路径启动...")
        # 直接从路径启动企业微信
        if fun.start_wechat():
            print("✅ 企业微信启动成功，等待窗口出现...")
            time.sleep(3)  # 等待窗口出现

            # 启动后立即最大化窗口
            if fun.maximize_wechat_window():
                print("✅ 企业微信窗口已最大化")
            else:
                print("⚠️ 企业微信窗口最大化失败")
        else:
            print("❌ 企业微信启动失败")
            return False

    time.sleep(1)  # 短暂等待窗口稳定

    # 检查登录状态
    print("🔐 检查登录状态...")
    return check_login_status()


def check_login_status():
    """检查企业微信的登录状态 - 优化版本"""
    print("开始检查登录状态...")

    # 首先检查是否已经登录（查找主界面）
    print("检查是否已进入主界面...")
    try:
        main_interface_location = pyautogui.locateOnScreen("static/images/wechat_if.png", confidence=0.7)
        if main_interface_location:
            print("✓ 检测到主界面，企业微信已登录")
            return True
    except Exception as e:
        print(f"检查主界面时出错: {e}")

    # 如果没有主界面，检查扫码界面
    print("未检测到主界面，检查扫码界面...")
    scan_detected = False
    max_attempts = 10  # 减少尝试次数，避免卡住太久
    no_scan_count = 0

    for i in range(max_attempts):
        wait_if_paused()  # 检查暂停状态

        try:
            # 使用较低的置信度，提高匹配成功率
            scan_location = pyautogui.locateOnScreen("static/images/saoma.png", confidence=0.7)
            if scan_location:
                if not scan_detected:
                    print("✓ 检测到扫码界面，等待用户扫码登录...")
                    scan_detected = True
                    time.sleep(2)  # 短暂等待
                else:
                    # 仍在扫码界面，继续等待
                    print(f"仍在扫码界面，等待中... ({i+1}/{max_attempts})")
                    time.sleep(2)
                no_scan_count = 0  # 重置计数器
                continue
            else:
                no_scan_count += 1
                if scan_detected and no_scan_count >= 3:
                    # 扫码界面连续3次未检测到，可能已登录
                    print("扫码界面消失，用户可能已完成登录")
                    break
                elif not scan_detected:
                    print(f"未检测到扫码界面，继续等待... ({i+1}/{max_attempts})")
                    time.sleep(1)

        except Exception as e:
            print(f"检查扫码状态时出错: {e}")
            if scan_detected:
                no_scan_count += 1
                if no_scan_count >= 3:
                    print("扫码界面消失，用户可能已完成登录")
                    break
            time.sleep(1)

    # 最终检查主界面
    print("最终检查主界面...")
    try:
        main_interface_location = pyautogui.locateOnScreen("static/images/wechat_if.png", confidence=0.7)
        if main_interface_location:
            print("✓ 检测到主界面，企业微信初始化完成")
            return True
        else:
            print("⚠ 未检测到主界面，企业微信可能未完全启动或登录")
            # 即使没有检测到主界面，也返回True，让程序继续运行
            # 用户可以在程序运行过程中手动处理登录问题
            print("继续执行程序，请确保企业微信已正确登录")
            return True
    except Exception as e:
        print(f"最终检查主界面时出错: {e}")
        print("继续执行程序，请确保企业微信已正确登录")
        return True


# 主函数
def main(skip_screenshots=False):
    # wait_if_paused()  # 检查暂停状态
    # if check_should_stop(): return  # 检查停止信号
    
    # mouse_fun.move_mouse_to_position(0.1,0.5)
    # wait_if_paused()  # 检查暂停状态
    # if check_should_stop(): return  # 检查停止信号
    
    # if mouse_fun.move_mouse_to_image("static/images/group.jpg", 0.9) is None:
    #     #如果没在列表找到群组，则滚动列表
    #     mouse_fun.move_mouse_to_image("static/images/scroll.jpg", 0.9)
    #     pyautogui.drag(0, -1080, duration=2)

    # time.sleep(1)

    # wait_if_paused()  # 检查暂停状态
    # if check_should_stop(): return  # 检查停止信号
    
    # # 再次查找群组
    # mouse_fun.move_mouse_to_image("static/images/group.jpg",0.9)
    # pyautogui.click(clicks=1, button='left')
    # time.sleep(1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    # 移动到屏幕中间
    print("移动到最新消息位置")
    mouse_fun.move_mouse_to_position(0.5,0.5)
    mouse_fun.move_mouse_to_image("static/images/scroll3.jpg",0.95)
    time.sleep(1)
    pyautogui.drag(0, 600, duration=2)
    # 开始查找转发消息
    mouse_fun.move_mouse_to_position(0.5,0.5)
    mouse_fun.find_message_position()
    pyautogui.click(clicks=1, button='right')
    time.sleep(1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    # 多选按钮
    mouse_fun.move_mouse_to_image("static/images/selectAll.png",0.8)
    pyautogui.click(clicks=1, button='left')
    time.sleep(1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    # 向下选择
    mouse_fun.move_mouse_to_image("static/images/sel_down.jpg",0.8)
    pyautogui.click(clicks=1, button='left')
    time.sleep(1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    # 主条      
    mouse_fun.move_mouse_to_image("static/images/zhutiao.jpg",0.8)
    pyautogui.click(clicks=1, button='left')
    time.sleep(1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    # 滚动
    mouse_fun.move_mouse_to_position(0.45,0.5)
    mouse_fun.move_mouse_to_image("static/images/scroll2.jpg",0.9)
    pyautogui.drag(0, 800, duration=1)
    arr=[]

    # 点击多选框
    for i in range(9):
        wait_if_paused()  # 检查暂停状态
        if check_should_stop(): return  # 检查停止信号
        
        mouse_fun.move_mouse_to_image("static/images/checkboxs.jpg",0.9,False)
        pyautogui.click(clicks=1, button='left')
        x,y=pyautogui.position()
        arr.append(y)
        if i==1 and not skip_screenshots:
            stop_x=x
            stop_y=arr[1]-arr[0]
            mouse_fun.move_mouse_to_coordinates(x,arr[0]+stop_y/2)
             # 保存第一次转发的截图
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2),260,int(stop_y)))
            screenshot.save(f"static/images/stop.png")
            # 2次确定
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2+stop_y),260,int(stop_y)))
            screenshot.save(f"static/images/stop2.png")
             # 3次确定
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2+stop_y*2),260,int(stop_y)))
            screenshot.save(f"static/images/stop3.png")
             # 4次确定
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2+stop_y*3),260,int(stop_y)))
            screenshot.save(f"static/images/stop4.png")
             # 5次确定
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2+stop_y*4),260,int(stop_y)))
            screenshot.save(f"static/images/stop5.png")
             # 6次确定
            screenshot = pyautogui.screenshot(region=(x,int(arr[0]+stop_y/2+stop_y*5),260,int(stop_y)))
            screenshot.save(f"static/images/stop6.png")
        elif i==1 and skip_screenshots:
            stop_x=x
        time.sleep(0.1)

    wait_if_paused()  # 检查暂停状态
    if check_should_stop(): return  # 检查停止信号
    
    mouse_fun.move_mouse_to_image("static/images/send.jpg",0.9)
    time.sleep(0.5)
    pyautogui.click(clicks=1, button='left')
    # mouse_fun.move_mouse_to_image("static/images/scroll2.jpg",0.8,False)
    # pyautogui.drag(0,-50, duration=1)
    time.sleep(2)
    
    if check_should_stop(): return  # 检查停止信号
    send_message(arr,stop_x)
    return arr,stop_x


# 转发开始
def send_message(arr,stop_x):
    for i in range(70):
        wait_if_paused()  # 检查暂停状态
        if check_should_stop(): return  # 检查停止信号
        
        print(f"第{i+1}次转发:")

        mouse_fun.move_mouse_to_image('static/images/message.jpg',0.9)
        time.sleep(0.5)
        if check_should_stop(): return  # 检查停止信号
        
        pyautogui.click(clicks=1, button='right')
        time.sleep(0.5)
        wait_if_paused()  # 检查暂停状态
        if check_should_stop(): return  # 检查停止信号
        
        mouse_fun.move_mouse_to_image('static/images/selectAll.png',0.9)
        time.sleep(0.2)
        pyautogui.click(clicks=1, button='left')
        time.sleep(0.2)
        wait_if_paused()  # 检查暂停状态
        if check_should_stop(): return  # 检查停止信号
        
        mouse_fun.move_mouse_to_image('static/images/sel_down.jpg',0.9)
        pyautogui.click(clicks=1, button='left')
        mouse_fun.move_mouse_to_image("static/images/zhutiao.jpg",0.8)
        pyautogui.click(clicks=1, button='left')
        mouse_fun.move_mouse_to_position(0.5,0.5)
        mouse_fun.move_mouse_to_image("static/images/scroll2.jpg",0.8)
        pyautogui.drag(0, 800, duration=1)
        
        if check_should_stop(): return  # 检查停止信号
        
        for j in range(9):
            time.sleep(0.1)        # 等待0.1秒让滚动生效
            wait_if_paused()  # 检查暂停状态
            if check_should_stop(): return  # 检查停止信号
            
            mouse_fun.move_mouse_to_coordinates(stop_x,arr[j])
            pyautogui.click(clicks=1, button='left')

        time.sleep(1)
        print("正在使用多层级置信度比对...")
        
        # 使用新的多层级置信度比对函数
        if check_stop_signals_multi_level():
            return  # 检测到停止信号，直接返回，停止程序
# 禁止发群
        try:
            if pyautogui.locateOnScreen("static/images/error1.png", 0.8):
                print("检测到小店数据群在转发列表内！无法发送！")
                return  # 直接返回，停止程序
        except Exception as e:
            print(f"检测error1图片时出错: {e}")

        try:
            if pyautogui.locateOnScreen("static/images/error3.png", 0.8):
                print("检测到小店数据群在转发列表内！无法发送！")
                return  # 直接返回，停止程序
        except Exception as e:
            print(f"检测error3图片时出错: {e}")
        wait_if_paused()  # 检查暂停状态
        if check_should_stop(): return  # 检查停止信号
        
        mouse_fun.move_mouse_to_image("static/images/send.jpg",0.8)
        time.sleep(0.1)
        pyautogui.click(clicks=1, button='left')
        time.sleep(4)
        
        if check_should_stop(): return  # 检查停止信号
    
def reset_state():
    """重置所有全局状态到初始值"""
    global is_paused, diaoxian_detected, monitor_active, should_stop
    
    print("正在重置程序状态...")
    
    # 重置暂停状态
    is_paused = False
    
    # 重置掉线检测状态
    diaoxian_detected = False
    
    # 重置停止标志
    should_stop = False
    
    # 停止监控
    monitor_active = False
    
    # 等待监控线程结束
    if monitor_thread and monitor_thread.is_alive():
        time.sleep(0.5)  # 给监控线程一点时间结束
    
    print("程序状态已重置完成")
    
if __name__ == "__main__":
    print("程序启动，按F8键可以暂停/继续程序执行")
    
    # 启动掉线监控
    start_monitoring()
    
    while True:
        try:
            # 初始化企业微信
            if not init():
                print("企业微信初始化失败，程序退出")
                break
            
            time.sleep(3)
            
            # 检查是否因为掉线检测而重新开始
            if diaoxian_detected:
                print("检测到掉线后重新开始，跳过截图步骤...")
                main(skip_screenshots=True)
                # 重置掉线检测标志
                diaoxian_detected = False
            else:
                main()
            
            # 如果程序正常结束，退出循环
            break
            
        except Exception as e:
            print(f"程序执行出错: {e}")
            if diaoxian_detected:
                print("等待用户按F8重新开始...")
                while is_paused:
                    time.sleep(0.1)
                # 重置掉线检测标志
                diaoxian_detected = False
            else:
                break